#!/usr/bin/perl
use Net::Delicious;
use Log::Dispatch::Screen;
use LWP::UserAgent;
use HTTP::Request;
use URI::URL qw(url);
use DateTime;
use DateTime::Format::W3CDTF;

my $cfg = new Config::Simple("$ENV{HOME}/freshnious.ini");
if ($cfg->param("debug")) {
   printf("logging in as '%s'\n", $cfg->param("user"));
   printf("logging in with pswd '%s'\n", $cfg->param("pswd"));
}

my $del = Net::Delicious->new ( $cfg );

my($url, $dt, %Date, %Posted);
my $ua = LWP::UserAgent->new();
my $f = DateTime::Format::W3CDTF->new;


foreach my $p ($del->all_posts_for_tag ( { tag =>"freshnious"} )) {
   $url = url($p->href());
   $tags = $p -> tags();
   if ($cfg->param("debug")) {
      print $p->description ().":".$p->time ().":".$p->href ()."\n";
   }
   my $dt = $f->parse_datetime( $p->time() );
   $Posted { $url } = $dt;
   #next unless $url->scheme = ~/^(file | https ?) $ /;
   my $ans = $ua->request (HTTP::Request->new ("HEAD", $url));
   if ($ans->is_success)
   {
      if (defined($ans->last_modified)) 
      {
	 $Date {$url} = DateTime->from_epoch(epoch => $ans->last_modified);

	 if ($Date{$url} != $Posted{$url}) {

	    printf "Upd %-25s Was %-25s %s\n", 
		   $Date{$url}   ? ($Date{$url}->datetime())."Z" : "<NONE SPECIFIED>", 
		   $Posted{$url} ? ($Posted{$url}->datetime()."Z") : "<Never posted?>",
		   $url;

	    $del->add_post({ 'url' => $url,
		  'description' => $p -> description(),
		  'extended' => $p -> extended(),
		  'tags' => $tags,
		  'dt' => $Date{$url}->datetime()."Z",
		  'replace' => 1,
		  'shared' => $p->shared()
		  });

	 }
      } else {
	 $tags = $p -> tags();
	 $tags =~ s/freshnious/stalenious/;

	 $del->add_post({ 'url' => $url,
	       'description' => $p -> description(),
	       'extended' => $p -> extended(),
	       'tags' => $tags,
	       'dt' => $Posted{$url}->datetime()."Z",
	       'replace' => 1,
	       'shared' => $p->shared()
	       });

      }
   } else {
	 print STDERR "$url: Error [", $ans->code, "] ", $ans->message, "!\n";
   }

}
